const cloud = require("wx-server-sdk");
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
// 获取用户信息并存储到users集合
const getUserInfo = async (event) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  
  try {
    // 检查users集合是否存在，如果不存在则创建
    try {
      await db.collection('users').where({ _openid: openid }).get();
    } catch (error) {
      if (error.errCode === 'DATABASE_COLLECTION_NOT_EXIST') {
        await db.createCollection('users');
      }
    }
    
    // 优先查询数据库中已存储的用户信息
    const userRes = await db.collection('users')
      .where({ _openid: openid })
      .get();
    
    const now = new Date();
    let nickname = '微信用户';
    let avatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
    
    // 如果数据库中有用户信息，使用数据库中的信息
    if (userRes.data.length > 0 && userRes.data[0].nickname) {
      nickname = userRes.data[0].nickname;
      avatarUrl = userRes.data[0].avatarUrl || avatarUrl;
    } else if (event.userInfo) {
      // 如果数据库中没有用户信息，但前端传递了用户信息，使用前端传递的信息
      const userInfo = event.userInfo;
      nickname = userInfo.nickName || userInfo.nickname || nickname;
      avatarUrl = userInfo.avatarUrl || avatarUrl;
    }
    
    if (userRes.data.length === 0) {
      // 用户不存在，创建新用户
      await db.collection('users').add({
        data: {
          _openid: openid,
          nickname: nickname,
          avatarUrl: avatarUrl,
          createTime: now,
          updateTime: now
        }
      });
    } else {
      // 用户已存在，更新用户信息（只有当有新的用户信息时才更新）
      if (event.userInfo) {
        await db.collection('users')
          .where({ _openid: openid })
          .update({
            data: {
              nickname: nickname,
              avatarUrl: avatarUrl,
              updateTime: now
            }
          });
      }
    }
    
    return {
      openid: openid,
      appid: wxContext.APPID,
      unionid: wxContext.UNIONID,
      nickname: nickname,
      avatarUrl: avatarUrl
    };
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 即使失败，也返回基本信息
    return {
      openid: openid,
      appid: wxContext.APPID,
      unionid: wxContext.UNIONID,
      nickname: '微信用户',
      avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
    };
  }
};

// 获取openid
const getOpenId = async () => {
  // 获取基础信息
  const wxContext = cloud.getWXContext();
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
};

// 获取小程序二维码
const getMiniProgramCode = async () => {
  // 获取小程序二维码的buffer
  const resp = await cloud.openapi.wxacode.get({
    path: "pages/index/index",
  });
  const { buffer } = resp;
  // 将图片上传云存储空间
  const upload = await cloud.uploadFile({
    cloudPath: "code.png",
    fileContent: buffer,
  });
  return upload.fileID;
};

// 创建集合
const createCollection = async (event) => {
  try {
    const { collectionName } = event;
    console.log('开始创建集合:', collectionName);
    
    // 创建集合
    const createRes = await db.createCollection(collectionName);
    console.log('集合创建结果:', createRes);
    
    return {
      success: true,
      collectionName,
      message: `集合${collectionName}创建成功`
    };
  } catch (e) {
    console.error('创建集合错误:', e);
    return {
      success: false,
      error: e,
      message: `集合${event.collectionName}创建失败: ${e.message}`
    };
  }
};

// 初始化所有集合
const initCollections = async () => {
  try {
    const collections = ['banners', 'comments', 'visitor_records', 'lalayingwu'];
    const results = [];
    
    for (const collectionName of collections) {
      try {
        console.log('检查集合是否存在:', collectionName);
        
        // 先尝试获取集合信息来检查是否存在
        try {
          const collectionInfo = await db.collection(collectionName).get();
          console.log('集合已存在:', collectionName);
          
          results.push({
            collectionName,
            success: true,
            exists: true,
            message: `集合${collectionName}已存在，跳过创建`
          });
          continue; // 跳过创建，继续下一个集合
        } catch (checkError) {
          // 如果获取集合信息失败，说明集合可能不存在
          if (checkError.errCode === 'DATABASE_COLLECTION_NOT_EXIST' || 
              checkError.errMsg && checkError.errMsg.includes('collection not exists')) {
            console.log('集合不存在，开始创建:', collectionName);
            
            // 创建集合
            const createRes = await db.createCollection(collectionName);
            console.log('集合创建结果:', createRes);
            
            results.push({
              collectionName,
              success: true,
              exists: false,
              message: `集合${collectionName}创建成功`
            });
          } else {
            // 其他错误，重新抛出
            throw checkError;
          }
        }
      } catch (e) {
        console.error(`处理集合${collectionName}错误:`, e);
        results.push({
          collectionName,
          success: false,
          error: e.message,
          message: `集合${collectionName}处理失败: ${e.message}`
        });
      }
    }
    
    // 计算统计信息
    const createdCount = results.filter(r => r.success && !r.exists).length;
    const existingCount = results.filter(r => r.success && r.exists).length;
    const failedCount = results.filter(r => !r.success).length;
    
    return {
      success: failedCount === 0, // 只有所有操作都成功才算完全成功
      results,
      statistics: {
        total: collections.length,
        created: createdCount,
        existing: existingCount,
        failed: failedCount
      },
      message: `集合初始化完成: 创建${createdCount}个, 已存在${existingCount}个, 失败${failedCount}个`
    };
  } catch (e) {
    console.error('初始化集合错误:', e);
    return {
      success: false,
      error: e,
      message: `集合初始化失败: ${e.message}`
    };
  }
};

// const getOpenId = require('./getOpenId/index');
// const getMiniProgramCode = require('./getMiniProgramCode/index');
// const createCollection = require('./createCollection/index');
// const sumRecord = require('./sumRecord/index');
// const fetchGoodsList = require('./fetchGoodsList/index');
// const genMpQrcode = require('./genMpQrcode/index');
// 云函数入口函数

// 删除鹦鹉关联评论
const deleteComments = async (event) => {
  try {
    const { parrotId } = event;
    // 查询关联评论
    const commentsRes = await db.collection('comments')
      .where({ parrotId })
      .get();
    
    // 收集评论图片
    const filesToDelete = commentsRes.data
      .flatMap(comment => comment.images || []);
    
    // 批量删除图片
    if (filesToDelete.length > 0) {
      await cloud.deleteFile({ fileList: filesToDelete });
    }
    
    // 删除评论记录
    await db.collection('comments')
      .where({ parrotId })
      .remove();
    
    return { success: true, deletedCount: commentsRes.data.length };
  } catch (e) {
    return { success: false, error: e.message };
  }
};

// 删除单个评论（管理员权限验证）
const deleteSingleComment = async (event) => {
  try {
    const { commentId } = event;
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 验证管理员权限
    const adminCheck = await db.collection('adminopenid')
      .where({ _openid: openid })
      .count();
    
    if (adminCheck.total === 0) {
      return { success: false, error: '权限不足，只有管理员可以删除评论' };
    }
    
    // 获取评论详情
    const commentRef = db.collection('comments').doc(commentId);
    const commentRes = await commentRef.get();
    
    if (!commentRes.data) {
      return { success: false, error: '评论不存在' };
    }
    
    const comment = commentRes.data;
    
    // 删除评论中的图片文件
    if (comment.images && comment.images.length > 0) {
      await cloud.deleteFile({ fileList: comment.images });
    }
    
    // 删除评论记录
    await commentRef.remove();
    
    return { success: true, message: '评论删除成功' };
  } catch (e) {
    console.error('删除评论错误:', e);
    return { success: false, error: e.message };
  }
};

// 更新评论内容（管理员权限验证）
const updateComment = async (event) => {
  try {
    const { commentId, content, images } = event;
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 验证管理员权限
    const adminCheck = await db.collection('adminopenid')
      .where({ _openid: openid })
      .count();
    
    if (adminCheck.total === 0) {
      return { success: false, error: '权限不足，只有管理员可以编辑评论' };
    }
    
    // 更新评论内容
    await db.collection('comments')
      .doc(commentId)
      .update({
        data: {
          content: content,
          images: images || [],
          updateTime: db.serverDate()
        }
      });
    
    return { success: true, message: '评论更新成功' };
  } catch (e) {
    console.error('更新评论错误:', e);
    return { success: false, error: e.message };
  }
};

// 删除评论图片（管理员权限验证）
const deleteCommentImage = async (event) => {
  try {
    const { imageUrls } = event;
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 验证管理员权限
    const adminCheck = await db.collection('adminopenid')
      .where({ _openid: openid })
      .count();
    
    if (adminCheck.total === 0) {
      return { success: false, error: '权限不足，只有管理员可以删除评论图片' };
    }
    
    // 删除图片文件
    if (imageUrls && imageUrls.length > 0) {
      await cloud.deleteFile({ fileList: imageUrls });
    }
    
    return { success: true, message: '图片删除成功', deletedCount: imageUrls.length };
  } catch (e) {
    console.error('删除评论图片错误:', e);
    return { success: false, error: e.message };
  }
};

exports.main = async (event, context) => {
  switch (event.type) {
    case "getOpenId":
      return await getOpenId();
    case "getMiniProgramCode":
      return await getMiniProgramCode();
    case "createCollection":
      return await createCollection(event);
    case "getUserInfo":
      return await getUserInfo(event);
    case "deleteComments":
      return await deleteComments(event);
    case "deleteSingleComment":
      return await deleteSingleComment(event);
    case "updateComment":
      return await updateComment(event);
    case "deleteCommentImage":
      return await deleteCommentImage(event);
    case "initCollections":
      return await initCollections();
  }
};
